package app

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"encoding/json"
	"time"
)

//用户登录
func (G *Global) Login(w http.ResponseWriter, r *http.Request) {

	if r.Method == "GET" {
		if t, err := template.ParseFiles("templates/login/index.html"); err == nil {
			G.PageTitle = "登录"
			t.Execute(w, G)
		} else {
			log.Println(err)
			fmt.Fprintln(w, err)
		}
	} else if r.Method == "POST" {
		G.Info = make(map[string]string)
		user_name := r.PostFormValue("user_name")
		password := r.PostFormValue("password")

		G.UserInfo.UserName = user_name //初始化用户信息
		G.UserInfo.Passwd = G.UserInfo.PasswdMD5(password)
		G.UserInfo.AuthToken = G.RandStr(64)

		if UserInfo, Err := G.SelectOne("SELECT * FROM users WHERE user_name=?", user_name); Err != nil { //查询用户信息
			log.Println(Err)
			fmt.Fprintln(w, Err)
		} else {
			if UserInfo["passwd"] == G.UserInfo.Passwd { //判断密码是否正确
				if UserInfo["status"] == "1" { //判断是否有登录权限
					G.Info["Login_Message"] = "该账户被禁用，请联系管理员"
				} else if UserInfo["status"] == "0" {
					//写入redis
					if PremsInfo, Err := G.SelectAll("SELECT menu_id FROM permissions where role_id =?", UserInfo["role_id"]); Err == nil { //查询用户权限信息
						G.UserInfo.Prems = *PremsInfo
						G.UserInfo.Role = UserInfo["role_id"]

						user_json, _ := json.Marshal(G.UserInfo)
						if err := G.Redis.Set(G.UserInfo.UserName, string(user_json), G.CookieExpiration); err == nil { //写入redis
							http.SetCookie(w, &http.Cookie{Name: "AuthToken", Value: G.UserInfo.AuthToken, Path: "/", MaxAge: 0})
							http.SetCookie(w, &http.Cookie{Name: "UserName", Value: G.UserInfo.UserName, Path: "/", MaxAge: 0}) //设置浏览器cookie
							if _, Err := G.DB.Update("UPDATE users SET login_time=? WHERE user_name =?", time.Now().Format("2006-01-02 15:04:05"), user_name); err == nil { //更新用户最后登录时间
								http.Redirect(w, r, "/", http.StatusFound)
							} else {
								log.Println(Err)
								fmt.Fprintln(w, Err)
							}
							//进入到主页
						} else {
							log.Println("redis存cookie失败" + err.Error())
							G.Info["Login_Message"] = "cookie写入redis失败"
						}
					} else {
						log.Println(Err)
						fmt.Fprintln(w, Err)
					}

				}
			} else {
				G.Info["Login_Message"] = "账号或密码错误"
			}
			if t, Err := template.ParseFiles("templates/login/index.html"); Err == nil {
				t.Execute(w, G)
			} else {
				log.Println(Err)
				fmt.Fprintln(w, Err)
			}

		}
	}
}

//用户注销登录
func (G *Global) Logout(w http.ResponseWriter, r *http.Request) {

	G.Redis.Del(G.UserInfo.UserName)                                          //删除redis cookie
	http.SetCookie(w, &http.Cookie{Name: "AuthToken", Path: "/", MaxAge: -1}) //设置浏览器cookie
	http.SetCookie(w, &http.Cookie{Name: "UserName", Path: "/", MaxAge: -1})  //设置浏览器cookie
	http.Redirect(w, r, "/login", http.StatusFound)                           //返回登录页面
}
